<template>
  <div class="dialog-container">
    <div class="dialog-content">
      <el-form ref="form" :rules="rules" size="mini" :model="form" label-width="80px">
        <el-form-item prop="name" label="群体名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item prop="rules" label="选择标签"> </el-form-item>
        <div class="label-list">
          <div class="label-item" v-for="item in labelList" :key="item.id">
            <div class="label-title">
              {{ item.name }}
              <div class="icon">
                <i v-if="item.selected" class="el-icon-delete" @click="handleDelete(item)"></i>
                <i v-else class="el-icon-circle-plus-outline" @click="handleSelect(item)"></i>
              </div>
            </div>
            <div class="tag-list" v-if="item.selected">
              <el-tag :class="{ active: tag.selected }" @click="handleTagSelect(tag)" v-for="tag in item.children" :key="tag.id" type="info" effect="plain">{{ tag.name }}</el-tag>
            </div>
          </div>
        </div>
        <el-form-item prop="recycle_prefer" label="回收偏好">
          <el-select v-model="form.recycle_prefer" placeholder="请选择" multiple filterable style="width: 100%">
            <el-option v-for="(item, index) in preferList" :label="item" :value="item" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="recycle_zones" label="回收区域">
          <el-cascader size="mini" v-model="form.recycle_zones" clearable :options="areaOption" :props="areaProps" style="width: 100%"></el-cascader>
        </el-form-item>
        <el-form-item style="margin-bottom: 0; margin-top: 40px">
          <div class="panel-line flex-end">
            <el-button @click="onCancel">取消</el-button>
            <el-button v-if="editModel === 'edit'" type="danger" @click="onDelete">删除</el-button>
            <el-button :loading="loading" type="primary" @click="onSubmit">保存</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { apiLabelSelect, apiLabelRecycleSelect, apiLabelGroupSave, apiLabelGroupDetail, apiLabelGroupDel } from '@/api/dataStatistics'

export default {
  name: 'DialogAdd',
  props: {
    id: String,
  },
  data() {
    return {
      loading: false,
      editModel: 'add',
      form: {
        name: '',
        rules: [],
        recycle_prefer: [],
        recycle_zones: [],
      },
      labelList: [],
      preferList: [],
      areaOption: [],
      areaProps: { value: 'code', label: 'name', checkStrictly: true, multiple: true },
      rules: {
        name: [{ required: true, message: '请输入群体名称', trigger: 'blur' }],
        rules: [{ required: true, message: '请选择标签', trigger: 'blur' }],
      },
    }
  },
  watch: {
    labelList: {
      handler(value) {
        this.form.rules = []
        value.forEach((item) => {
          if (item.selected) {
            item.children.forEach((item2) => {
              if (item2.selected) {
                this.form.rules.push(item2.id)
              }
            })
          }
        })
      },
      deep: true,
    },
  },
  mounted() {
    this.getSelect()
  },
  destroyed() {},
  methods: {
    getSelect() {
      apiLabelSelect().then((res) => {
        res.data.forEach((item) => {
          item.selected = false
          item.children.forEach((item2) => {
            item2.selected = false
          })
        })
        this.labelList = res.data
        if (this.id) {
          this.editModel = 'edit'
          this.getDetail()
        } else {
          this.editModel = 'add'
        }
      })
      apiLabelRecycleSelect().then((res) => {
        this.preferList = res.data
      })
      this.$store.dispatch('select/getCityList').then((res) => {
        this.areaOption = res
      })
    },
    // 获取详情
    getDetail() {
      apiLabelGroupDetail({ id: this.id }).then((res) => {
        this.detail = res.data
        this.setDetail()
      })
    },
    setDetail() {
      this.form.id = this.id
      this.form.name = this.detail.name
      this.form.rules = this.detail.rules
      this.form.recycle_prefer = this.detail.recycle_prefer ? this.detail.recycle_prefer.split(',') : []
      this.form.recycle_zones = this.detail.recycle_zones ? this.detail.recycle_zones.split('|') : []
      this.labelList.forEach((item) => {
        item.children.forEach((item2) => {
          if (this.form.rules.includes(item2.id)) {
            item2.selected = true
            item.selected = true
          }
        })
      })
    },
    // 取消
    onCancel() {
      this.$emit('close')
    },
    formatSubmitData() {
      let submitData = {}
      if (this.editModel === 'edit') {
        submitData.id = this.form.id
      }
      submitData.name = this.form.name
      submitData.recycle_prefer = this.form.recycle_prefer
      submitData.recycle_zones = this.form.recycle_zones.join('|')
      submitData.rules = []
      this.labelList.forEach((item) => {
        if (item.selected) {
          item.children.forEach((item2) => {
            if (item2.selected) {
              submitData.rules.push(item2.id)
            }
          })
        }
      })
      console.log(submitData)
      return submitData
    },
    // 保存
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          apiLabelGroupSave(this.formatSubmitData())
            .then((res) => {
              this.$message({
                message: '保存成功',
                type: 'success',
              })
              setTimeout(() => {
                this.loading = false
                this.$emit('success')
              }, 1000)
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    },
    onDelete() {
      this.$confirm('确认要删除这个群体吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        apiLabelGroupDel({ id: this.form.id }).then((res) => {
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
          setTimeout(() => {
            this.$emit('success')
          }, 1000)
        })
      })
    },
    handleSelect(item) {
      item.selected = true
    },
    handleDelete(item) {
      item.selected = false
    },
    handleTagSelect(tag) {
      tag.selected = !tag.selected
    },
  },
}
</script>

<style scoped lang="scss">
.label-list {
  margin-bottom: 20px;
}
.label-item {
  margin-top: 16px;
  padding-left: 16px;
}
.label-title {
  display: flex;
  align-items: center;
  .icon {
    font-size: 16px;
    margin-left: 10px;
    cursor: pointer;
    &:hover {
      color: #f56c6c;
    }
    .el-icon-circle-plus-outline:hover {
      color: #5db42c;
    }
  }
}
.tag-list {
  margin-top: 8px;
  .el-tag {
    margin-right: 4px;
    margin-bottom: 2px;
    cursor: pointer;
    &.active {
      color: #5db42c;
      border-color: #5db42c;
    }
  }
}
</style>
